﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KKU.RBSFPP.Shared.DAC;
using KKU.RBSFPP.Web.Administrator.Models;

namespace KKU.RBSFPP.Web.Administrator.Controllers
{
    [Authorize]
    public class BuyController : Controller
    {
        private RBSFPPModelContainer db = new RBSFPPModelContainer();

        //
        // GET: /Buy/

        public ActionResult Index()
        {
            //var producttrackings = db.ProductTrackings.Include("Product").Include("ProductPricingPerUnit").Include("Member");
            //return View(producttrackings.ToList());

            var now = DateTime.Today;

            var result = from it in db.ProductTrackings.Include("Product").Include("ProductPricingPerUnit").Include("Member")
                         where (it.CreateOn.Day == now.Day) && (it.CreateOn.Month == now.Month) && (it.CreateOn.Year == now.Year)
                                && it.Action == "B"
                         select it;

            // (Model ไม่รอบรับ)
            //ViewBag.Summary = 9;

            // ยอดซื้อภายในวันนี้
            if (result.Any())
            {
                var totalPrice = result.Sum(it => it.Unit * it.ProductPricingPerUnit.PurchasingPrice);
                ViewBag.Summary = totalPrice;
            }
            else
            {
                ViewBag.Summary = 0;
            }


            return View(result.ToList());
        }

        //
        // GET: /Buy/Details/5

        public ActionResult Details(int id = 0)
        {
            ProductTracking producttracking = db.ProductTrackings.Single(p => p.Id == id);
            if (producttracking == null)
            {
                return HttpNotFound();
            }
            return View(producttracking);
        }

        //
        // GET: /Buy/Create

        public ActionResult Create()
        {
            // สร้างตระกร้าเก็บสินค้า
            var cart = new List<ProductTracking>();
            TempData["Cart"] = cart;
            ViewBag.Cart = cart;

            // เตรียมข้อมูลสำหรับแสดงหน้าเว็บ
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username");
            return View();
        }

        //
        // POST: /Buy/Create

        [HttpPost]
        public ActionResult AddMoreItem(ProductTracking producttracking)
        {
            var cart = TempData["Cart"] as List<ProductTracking>;
            if (ModelState.IsValid)
            {
                // เอาข้อมูลที่เลือกไปเก็บไว้ในตระกร้าสินค้า
                
                producttracking.Product = db.Products.FirstOrDefault(it => it.Id == producttracking.ProductId);
                producttracking.ProductPricingPerUnit = db.Products.FirstOrDefault(it => it.Id == producttracking.ProductId).ProductPricingPerUnit;

                if (cart.Any(it => it.ProductId == producttracking.ProductId))
                {
                    var item = cart.FirstOrDefault(it => it.ProductId == producttracking.ProductId);
                    item.Unit += producttracking.Unit;
                }
                else
                {
                    cart.Add(producttracking);
                }
            }

            TempData["Cart"] = cart;
            ViewBag.Cart = cart;
   
            // เตรียมข้อมูลสำหรับแสดงหน้าเว็บ
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username");
            ViewBag.Summary = cart.Sum(it => it.Unit * it.ProductPricingPerUnit.PurchasingPrice);
            return View("Create");
        }

        public ActionResult RemoveItem(int id)
        {
            // เอาสินค้าที่ต้องการออกจากตระกร้า
            var cart = TempData["Cart"] as List<ProductTracking>;
            if (cart.Count > id)
            {
                cart.RemoveAt(id);
            }
            TempData["Cart"] = cart;
            ViewBag.Cart = cart;

            // เตรียมข้อมูลสำหรับแสดงหน้าเว็บ
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username");
            ViewBag.Summary = cart.Sum(it => it.Unit * it.ProductPricingPerUnit.PurchasingPrice);
            return View("Create");
        }




        [HttpPost]
        public ActionResult Confirm()
        {
            // เอาสินค้าจากตระกร้าไปเก็บลงฐานข้อมูล
            var cart = TempData["Cart"] as List<ProductTracking>;
            if (cart.Any())
            {
                var now = DateTime.Now;
                foreach (var item in cart)
                {
                    var newRecord = new ProductTracking
                    {
                        Action = "B",
                        CreateOn = now,
                        ProductPricingPerUnitId = db.Products.Where(it => it.Id == item.ProductId).Select(it => it.ProductPricingPerUnitId).FirstOrDefault(),
                        MemberId = db.Members.Where(it => it.Username == User.Identity.Name).FirstOrDefault().Id,
                        ProductId = item.Product.Id,
                        Unit = item.Unit
                    };
                    db.ProductTrackings.AddObject(newRecord);
                }
                db.SaveChanges();
            }
            return RedirectToAction("Index");

            //if (ModelState.IsValid)
            //{
                //producttracking.Action = "B";
                //producttracking.CreateOn = DateTime.Now;
                //// ดึงราคาต่อหน่วยตัวล่าสุด
                //{
                //    //producttracking.ProductId
                //    var productQry = from it in db.Products
                //                     where it.Id == producttracking.ProductId
                //                     select it.ProductPricingPerUnitId;

                //    producttracking.ProductPricingPerUnitId = productQry.FirstOrDefault();

                //    //producttracking.ProductPricingPerUnitId = producttracking.Product.ProductPricingPerUnitId;
                //    //producttracking.ProductPricingPerUnit = producttracking.Product.ProductPricingPerUnit;
                //}

                //// ดึงผู้ใช้ที่ทำรายการนี้
                //{
                //    var userQry = from it in db.Members
                //                  where it.Username == User.Identity.Name
                //                  select it;
                //    producttracking.Member = userQry.FirstOrDefault();
                //}

                //db.ProductTrackings.AddObject(producttracking);
                //db.SaveChanges();
                //return RedirectToAction("Index");
            //}

            //ViewBag.ProductId = new SelectList(db.Products, "Id", "Name", producttracking.ProductId);
            //ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits, "Id", "Name", producttracking.ProductPricingPerUnitId);
            //ViewBag.MemberId = new SelectList(db.Members, "Id", "Username", producttracking.MemberId);
            //return View(producttracking);
            //return View("Index");
        }

        //
        // GET: /Buy/Edit/5

        public ActionResult Edit(int id = 0)
        {
            ProductTracking producttracking = db.ProductTrackings.Single(p => p.Id == id);
            if (producttracking == null)
            {
                return HttpNotFound();
            }
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username", producttracking.MemberId);
            return View(producttracking);
        }

        //
        // POST: /Buy/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(ProductTracking producttracking)
        {
            if (ModelState.IsValid)
            {
                db.ProductTrackings.Attach(producttracking);
                db.ObjectStateManager.ChangeObjectState(producttracking, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ProductId = new SelectList(db.Products.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.ProductPricingPerUnitId = new SelectList(db.ProductPricingPerUnits.Where(it => it.DeleteOn.HasValue == false), "Id", "Name");
            ViewBag.MemberId = new SelectList(db.Members, "Id", "Username", producttracking.MemberId);
            return View(producttracking);
        }

        //
        // GET: /Buy/Delete/5

        public ActionResult Delete(int id = 0)
        {
            ProductTracking producttracking = db.ProductTrackings.Single(p => p.Id == id);
            if (producttracking == null)
            {
                return HttpNotFound();
            }
            return View(producttracking);
        }

        //
        // POST: /Buy/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            ProductTracking producttracking = db.ProductTrackings.Single(p => p.Id == id);
            db.ProductTrackings.DeleteObject(producttracking);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}